package cn.leedsoft.and.crimeintent.controller.crime_intent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import cn.leedsoft.and.crimeintent.R;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by leeds on 2016/8/9 10:24.
 */
public class DetailDateDialogFragment extends DialogFragment {
    private DatePicker mDatePicker;
    private Date mDate;
    public static final String INTENT_KEY_CRIME_DATE = "intent.key.crime.date";
    public static final String TAG = DetailDateDialogFragment.class.getSimpleName();

    public static DetailDateDialogFragment newInstance(Date date) {
        Bundle args = new Bundle();
        args.putSerializable(INTENT_KEY_CRIME_DATE, date);

        DetailDateDialogFragment fragment = new DetailDateDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDate = (Date) getArguments().getSerializable(INTENT_KEY_CRIME_DATE);
        final Calendar c = Calendar.getInstance();
        c.setTime(mDate);

        mDatePicker = new DatePicker(getActivity());
        mDatePicker.setId(R.id.detail_date_picker);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            mDatePicker.setCalendarViewShown(false);
        mDatePicker.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                c.set(year, monthOfYear, dayOfMonth);
                mDate.setTime(c.getTimeInMillis());
            }
        });

        return new AlertDialog.Builder(getActivity())
                .setView(mDatePicker)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sendResult();
                    }
                }).create();
    }

    private void sendResult() {//逻辑模块化
        if (getTargetFragment() == null) return;

        Intent intent = new Intent();
        intent.putExtra(INTENT_KEY_CRIME_DATE, mDate);

        getTargetFragment().onActivityResult(CrimeDetailFragment.REQ_CODE_DATE_DIALOG, Activity.RESULT_OK, intent);
    }
}
